package com.lovely602.ai.openai.controller.chat;


import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @author lizhixing
 */
@Slf4j
@RestController
@RequestMapping("/chat/model")
public class ChatModelController {

    @Autowired
    private ChatModel chatModel;

    @GetMapping("/chat01")
    public String chatModel01(@RequestParam(value = "msg") String msg) {

        String result = null;
        try {
            result = chatModel.call(msg);
        } catch (Exception e) {
            log.error("chatModel01 error ", e);
        }

        return result;
    }

    @GetMapping("/chat02")
    public String chatModel02(@RequestParam(value = "msg") String msg) {

        ChatResponse chatResponse = chatModel.call(new Prompt(
                        msg,
                        OpenAiChatOptions.builder()
                                .model("qwen-turbo")
                                .temperature(0.2)
                                .build()
                )
        );

        return chatResponse.getResult().getOutput().getText();
    }

    @GetMapping(value = "/chat03", produces = "text/html;charset=UTF-8")
    public Flux<String> chat03(@RequestParam(value = "msg") String msg) {

        return chatModel.stream(msg);

    }

    @GetMapping(value = "/stream", produces = "text/html;charset=UTF-8")
    public Flux<String> modelStream(@RequestParam(value = "msg") String msg, @RequestParam(value = "voice") String voice) {

        //设置用户输入信息
        String userText = """
                给我推荐北京的至少三种美食
                """;
        UserMessage userMessage = new UserMessage(msg);

        // 设置系统提示信息
        String systemText = """
                你是一个美食咨询助手，可以帮助人们查询美食信息。
                你的名字是小美,
                你应该用你的名字和{voice}的饮食习惯回复用户的请求。
                """;

        Map<String, Object> additionalVariables = new HashMap<>();
        additionalVariables.put("voice", voice);

        // 替换占位符
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
        Message systemMessage = systemPromptTemplate.createMessage(additionalVariables);

        // 封装提示词
        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));

        Flux<ChatResponse> chatResponseFlux = chatModel.stream(prompt);

        return chatResponseFlux.map(response -> (response.getResult() == null || response.getResult().getOutput() == null
                || response.getResult().getOutput().getText() == null) ? ""
                : response.getResult().getOutput().getText());

    }


    @GetMapping("/call")
    public String modelCall(@RequestParam(value = "msg") String msg, @RequestParam(value = "voice") String voice) {

        //设置用户输入信息
        String userText = """
                给我推荐北京的至少三种美食
                """;
        UserMessage userMessage = new UserMessage(msg);

        // 设置系统提示信息
        String systemText = """
                你是一个美食咨询助手，可以帮助人们查询美食信息。
                你的名字是小美,
                你应该用你的名字和{voice}的饮食习惯回复用户的请求。
                """;

        Map<String, Object> additionalVariables = new HashMap<>();
        additionalVariables.put("voice", voice);

        // 替换占位符
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
        Message systemMessage = systemPromptTemplate.createMessage(additionalVariables);

        // 封装提示词
        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));

        ChatResponse response = chatModel.call(prompt);
        List<Generation> results = response.getResults();

        return results.stream().map(x -> x.getOutput().getText()).collect(Collectors.joining(";"));
    }

}
